package be.jaisy.project.adapter.factory;

import java.util.HashMap;
import java.util.Map;

import org.osgi.framework.Bundle;
import org.osgi.framework.ServiceFactory;

import be.jaisy.project.adapter.IProjectDao;

/**
 * Creates a standalone DaoFactory that returns DAO beans for use in any
 * environment
 * 
 * @author Stany Blanvalet
 */
public abstract class DaoFactory implements ServiceFactory {
	/**
	 * Creates a standalone DaoFactory that returns unmanaged DAO beans for use
	 * in any environment Hibernate has been configured for. Uses
	 * HibernateUtil/SessionFactory and Hibernate context propagation
	 * (CurrentSessionContext), thread-bound or transaction-bound, and
	 * transaction scoped.
	 */
	public static final String HIBERNATE = "be.jaisy.project.adapter.factory.impl.HibernateDaoFactoryImpl";

	private static Map<String, DaoFactory> factories = new HashMap<String, DaoFactory>(); 
	
	/**
	 * Factory method for instantiation of concrete factories.
	 */
	public static DaoFactory instance(String factoryName, Bundle bundle) {
		
		DaoFactory factory = factories.get(factoryName);
		if(factory==null){
			try {
				Class factoryClass = bundle.loadClass(factoryName);
				factory = (DaoFactory) factoryClass.newInstance();
			} catch (Exception ex) {
				ex.printStackTrace();
				throw new RuntimeException("Couldn't create DaoFactory [" + factory + "]: " + ex.getMessage());
			}
			factories.put(factoryName, factory);			
		}
		return factory;
	}

	// Add your DAO interfaces here
	/**
	 * @return the singleton IProjectDao implementation
	 */
	public abstract IProjectDao getProjectDao();
}
